package com.lxy.code.service.impl;

import com.lxy.code.dao.LagouAuthCodeDao;
import com.lxy.code.pojo.LagouAuthCode;
import com.lxy.code.service.LagouAuthCodeService;
import com.lxy.code.service.SendCodeByEmailService;
import com.lxy.common.JsonResult;
import org.apache.commons.lang.time.DateUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

/**
 * @author 123
 * @date 2020/6/22 18:12
 * @description
 */
@Service
public class LagouAuthCodeServiceImpl implements LagouAuthCodeService {

    @Autowired
    private LagouAuthCodeDao lagouAuthCodeDao;

    @Reference(timeout = 3000)
    private SendCodeByEmailService sendCodeByEmailService;


    @Override
    public boolean sendCode(String email) {
        String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        if (sendCodeByEmailService.sendCode(email, code)) {
            saveCode(email, code);
            return true;
        }
        return false;
    }

    private void saveCode(String email, String code) {
        LagouAuthCode topByEmail = lagouAuthCodeDao.findTopByEmail(email);
        if (topByEmail != null) {
            topByEmail.setCode(code);
            topByEmail.setExpiretime(DateUtils.addMinutes(new Date(), 10));
            lagouAuthCodeDao.save(topByEmail);
        } else {
            LagouAuthCode lagouAuthCode = new LagouAuthCode();
            lagouAuthCode.setEmail(email);
            lagouAuthCode.setCode(code);
            Date now = new Date();
            lagouAuthCode.setCreatetime(now);
            lagouAuthCode.setExpiretime(DateUtils.addMinutes(now, 10));
            lagouAuthCodeDao.save(lagouAuthCode);
        }
    }

    @Override
    public JsonResult validateCode(String email, String code) {
        LagouAuthCode topByEmail = lagouAuthCodeDao.findTopByEmail(email);
        if (topByEmail == null) {
           return JsonResult.error("请先发送验证码");
        } else if (topByEmail.getExpiretime().before(new Date())) {
            return JsonResult.error("验证码已过期");
        } else if (!code.equals(topByEmail.getCode())) {
            return JsonResult.error("验证码不正确");
        }
        return JsonResult.ok("验证成功");
    }


    public static void main(String[] args) {
        System.out.println(DateUtils.addMinutes(new Date(), 10));
    }
}
